﻿using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;

namespace redis_microservice.Controllers
{
    /// <summary>
    /// 哈希 -> 常用于存储对象
    /// </summary>
    public class HashController(IConnectionMultiplexer connection) : BaseController(connection)
    {
        /// <summary>
        /// 获取所有字段和值
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Get(string key = "user:info:001")
        {
            var res = await _db0.HashGetAllAsync(key);

            return Ok(res.Select(x => new
            {
                Name = x.Name.ToString(),
                Value = x.Value.ToString()
            }));
        }

        /// <summary>
        /// 设置多个字段和值
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Set(string key = "user:info:001", string field = "name", string val = "666")
        {
            var user = new HashEntry[]
            {
                new(field, val)
            };

            await _db0.HashSetAsync(key, user); // 字段存在则更新值
            return Ok();
        }

        /// <summary>
        /// 获取单个字段的值
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetField(string key = "user:info:001", string field = "name")
        { 
            string? val = await _db0.HashGetAsync(key, field);
            return Ok(val);
        }

        /// <summary>
        /// 设置单个字段和值
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> SetField
            (string key = "user:info:001", string field = "name", string val = "666")
        {
            var res = await _db0.HashSetAsync(key, field, val); // 返回 false 表示字段存在且值已更新
            return Ok(res);
        }

        /// <summary>
        /// 删除单个字段
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DelField(string key = "user:info:001", string field = "name")
        {
            bool res = await _db0.HashDeleteAsync(key, field); // 返回 false 表示字段不存在
            return Ok(res);
        }
    }
}
